// 食物类
import Food from "./Food";
// 蛇
import Sanke from "./Sanke";
// 积分面板
import ScorePanel from "./ScorePanel";
// 游戏控制类
class GameControl{
  // 食物
  food:Food
  // 蛇
  sanke:Sanke
  // 积分面板
  scorcePanel:ScorePanel
  // 键盘按键
  direction:string = ''
  // 是否结束
  isLive:Boolean = true
  constructor(){
    this.food = new Food()
    this.sanke = new Sanke()
    this.scorcePanel = new ScorePanel()
    this.init()
  }
  // 初始化
  init(){
    /* 
        一般浏览器            IE
    上方按键 ArrowUp          Up 
    下方按键 ArrowDown       Down
    左方按键 ArrowLeft       Left
    右方按键 ArrowRight      Right
     */
    document.addEventListener('keyup',this.keyUpHandle('随便传个参',this))
    this.run()
  }
  // 键盘处理函数
  keyUpHandle(value,self){
    console.log(value+'-->此乃函数柯里化')
    let keyupList = ['ArrowUp','ArrowDown','ArrowLeft','ArrowRight','Up','Down','Left','Right']
    return (event)=>{
      if(keyupList.includes(event.key)){
        self.direction = event.key 
        if(!self.isLive){
          self.isLive = true
          self.run()
        }
      }
    }
  }
  // 移动
  run(){
    let x = this.sanke.X
    let y = this.sanke.Y
    switch(this.direction){
      case 'ArrowUp':
      case 'Up':
        y -= 10
        break
      case 'ArrowDown':
      case 'Down':
        y += 10
        break
      case 'ArrowLeft':
      case 'Left':
        x -= 10
        break
      case 'ArrowRight':
      case 'Right':
        x += 10
        break
    }
    // 是否吃到食物
    this.checkEat(x,y)
    try{
      // this.sanke.X = x
      // this.sanke.Y = y
      this.sanke.setXY('X',x)
      this.sanke.setXY('Y',y)
    }catch(e){
      this.isLive = false
      alert(e.message)
      // 清空积分和恢复关卡
      this.scorcePanel.addLevel(false)
      this.scorcePanel.addScore(false)
      // 清空身体
      this.sanke.clearBody()

    }
    this.isLive && setTimeout(this.run.bind(this),300 - (this.scorcePanel.getLevel() - 1) * 30)
  }
  // 是否吃到食物
  checkEat(x:number,y:number){
    if(x === this.food.X && y === this.food.Y){
      // 改变食物位置
      this.food.changeXY()
      // 分数增加
      this.scorcePanel.addScore(true)
      // 增加身体长度
      this.sanke.addBody()
    }
  }
}
export default GameControl